﻿using MediatR;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using RedDragon.Common.Domain.Supplier;
using RedDragon.Common.Dtos;
using RedDragon.ERP.ErroCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Supplieries
{
    /// <summary>
    /// 导出供应商信息
    /// </summary>
    public class ExportSupplierHandler : IRequestHandler<ExportSupplierCommand, FileExportResult>
    {
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ExportSupplierHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public ExportSupplierHandler(ISqlSugarClient db, ILogger<ExportSupplierHandler> logger)
        {
            _db = db;
            _logger = logger;
        }

        /// <summary>
        /// 导出供应商
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<FileExportResult> Handle(ExportSupplierCommand request, CancellationToken cancellationToken)
        {
            var result = new FileExportResult();
            try
            {
                //四表联查
                var query = await _db.Queryable<Suppliers, Classifications, Countrys, Citys>((s, t, g, c) => s.ClassificationId == t.ClassIficationsId && s.CountryId == g.CountryId && s.CityId == c.CityId).Where(s => s.IsSupplier == 1)
                    .Select((s, t, g, c) => new SupplierDto()
                    {
                        SupplierId = s.SupplierId,
                        SupplierCoding = s.SupplierCoding,
                        SupplierName = s.SupplierName,
                        SupplierDiff = s.SupplierDiff,
                        SupplierPhone = s.SupplierPhone,
                        SupplierAddress = s.SupplierAddress,
                        CountryId = s.CountryId,
                        CityId = s.CityId,
                        ClassificationId = s.ClassificationId,
                        SupplierLabel = s.SupplierLabel,
                        CompanyLogo = s.CompanyLogo,
                        Identification = s.Identification,
                        SupplierStatus = s.SupplierStatus,
                        IsSupplier = s.IsSupplier,
                        CreatedOwner = s.CreatedOwner,
                        CreatedTime = s.CreatedTime,
                        UpdateOwner = s.UpdateOwner,
                        UpdateTime = s.UpdateTime,
                        ExamineOwner = s.ExamineOwner,
                        ExamineTime = s.ExamineTime,
                        ClassIficationsName = t.ClassIficationsName,
                        CountryName = g.CountryName,
                        CityName = c.CityName,
                    }).ToListAsync();

                //创建一个新的Excel工作簿
                IWorkbook wb = new XSSFWorkbook();

                //在工作簿中创建一个新的Sheet
                ISheet sheet = wb.CreateSheet();

                //创建表头,第一行
                IRow row = sheet.CreateRow(0);

                //设置表头的各个列标题
                row.CreateCell(0).SetCellValue("序号");
                row.CreateCell(1).SetCellValue("供应商编码");
                row.CreateCell(2).SetCellValue("供应商名称");
                row.CreateCell(3).SetCellValue("供应商类型");
                row.CreateCell(4).SetCellValue("供应商地址");
                row.CreateCell(5).SetCellValue("供应商电话");
                row.CreateCell(6).SetCellValue("所在城市");
                row.CreateCell(7).SetCellValue("创建时间");
                row.CreateCell(8).SetCellValue("创建人");
                row.CreateCell(9).SetCellValue("状态");

                //初始化行索引
                int index = 0;//注意这里从0行开始 已经是表头了
                foreach (var item in query)
                {
                    //为每条记录创建一行
                    row = sheet.CreateRow(index);

                    //填充数据到各列
                    row.CreateCell(0).SetCellValue(item.SupplierId);
                    row.CreateCell(1).SetCellValue(item.SupplierCoding);
                    row.CreateCell(2).SetCellValue(item.SupplierName);
                    row.CreateCell(3).SetCellValue(item.SupplierDiff);
                    row.CreateCell(4).SetCellValue(item.SupplierAddress);
                    row.CreateCell(5).SetCellValue(item.SupplierPhone);
                    row.CreateCell(6).SetCellValue(item.CityName);
                    row.CreateCell(7).SetCellValue(item.CreatedTime.ToString());
                    row.CreateCell(8).SetCellValue(item.CreatedOwner);
                    row.CreateCell(9).SetCellValue(item.SupplierStatus == 1 ? "有效" : "无效");

                    //行索引递增
                    index++;
                }

                //将工作簿内容写入字节数组
                byte[] bytes;
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    bytes = ms.ToArray();
                }

                //获取.xlsx文件的MIME类型
                string mime = new FileExtensionContentTypeProvider().Mappings[".xlsx"];

                //设置导出结果对象的属性
                result.FileBytes = bytes;//文件字节内容
                result.MimeType = mime;//MIME类型
                result.FileName = "供应商信息.xlsx";//文件名
            }
            catch (Exception ex)
            {
                _logger.LogError("导出供应商信息异常" + ex.Message);
            }
            return result;
        }
    }
}
